package com.jxy.homepage.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jxy.BBM_info.BBM;
import com.jxy.BBM_info.BBM_table;
import com.jxy.BBM_info.utils.BBM_util;
import com.jxy.homepage.domain.User;
import com.jxy.homepage.mapper.UserMapper;
import com.jxy.homepage.security.jwt.JwtTokenUtils;
import com.jxy.homepage.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author J
 * @description 针对表【j_user】的数据库操作Service实现
 * @createDate 2022-01-06 13:47:45
 */
@Service
@Slf4j
@Transactional(rollbackFor = Exception.class)
public class UserServiceImpl extends ServiceImpl<UserMapper, User>
        implements UserService {
    private final JwtTokenUtils jwtTokenUtils;

    public UserServiceImpl(JwtTokenUtils jwtTokenUtils) {
        this.jwtTokenUtils = jwtTokenUtils;
    }

    @Override
    public String createToken(User user) {

        HashMap<String, Object> m1 = new HashMap<>(2);
        if (user.getEname() == null || user.getPassword() == null) {
            throw new RuntimeException("error");
        }
        Map<String, String> userMap = new HashMap<>(2);
        userMap.put("ENAME", user.getEname());
        userMap.put("PASSWORD", user.getPassword());
        QueryWrapper<User> wrapper = new QueryWrapper<>();
        wrapper.allEq(userMap);

        List<User> list = this.list(wrapper);

        Map<String, Object> map;
        if (list != null && list.size() > 0) {
            map = new HashMap<>(2);
            map.put("user", list.get(0).getCname());
            map.put("password", list.get(0).getPassword());
            m1.put("token", jwtTokenUtils.createToken(map));
            log.info(jwtTokenUtils.createToken(map));
        } else {
            throw new RuntimeException("error");
        }
        return JSON.toJSONString(m1);
    }

    @Override
    public BBM queryUserByName(String username) {
        BBM bbm = new BBM();
        try {
            QueryWrapper<User> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("ENAME", username);
            List<User> list = this.list(queryWrapper);
            BBM_table table = BBM_util.toTable(list, User.class);
            table.setName("USER_INFO");
            bbm.addTable(table);
        } catch (Exception e){
            bbm.getBbmInfo().setMessage(e.getMessage());
            bbm.getBbmInfo().setCode(-1);
        }
        return bbm;
    }
}




